package net.wanho.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import lombok.SneakyThrows;
import net.wanho.entity.User;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Author：汤小洋
 * Date：2023-08-29 10:23
 * Description：<描述>
 */
@RestController
public class EasyPOIController {

    @SneakyThrows
    @RequestMapping("/export")
    public void export(HttpServletResponse response) {
        List<User> list = new ArrayList<>();
        list.add(new User(1, "张三", "123456", 18, "aa@qq.com", LocalDateTime.now(), 0));
        list.add(new User(2, "李四", "123456", 18, "aa@qq.com", LocalDateTime.now(), 1));
        list.add(new User(3, "王五", "123456", 18, "aa@qq.com", LocalDateTime.now(), 0));

        ExportParams params = new ExportParams("用户信息表", "用户表");
        Workbook workbook = ExcelExportUtil.exportExcel(params, User.class, list);

        // 设置响应内容类型
        response.setContentType("application/x-excel");
        // 设置处理方式为附件，并指定文件名
        response.setHeader("Content-Disposition", "attachment;filename="+ new String("用户信息表.xlsx".getBytes("utf-8"), "iso-8859-1"));

        // 写到响应流中
        workbook.write(response.getOutputStream());
    }

    @SneakyThrows
    @RequestMapping("/import")
    // public AjaxResult importExcel(@RequestParam MultipartFile file) {
    public void importExcel(){
        FileInputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Downloads\\Document\\用户信息表.xlsx");

        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<User> list = ExcelImportUtil.importExcel(inputStream, User.class, params);
        list.forEach(System.out::println);
    }
}
